package com.hjl.sr.security.token;

import java.util.Iterator;
import java.util.UUID;
import java.util.concurrent.CopyOnWriteArrayList;

public class TokenGeneratorImpl implements TokenGenerator {

	private final int bufSize;
	
	public TokenGeneratorImpl(int bufSize) {
		this.bufSize = bufSize;
		growToken();
	}
	
	
	public TokenGeneratorImpl() {
		this(1024);
	}
	
	private volatile Iterator<String> tokenIterator;
	
	private synchronized void growToken() {
		if (tokenIterator != null && tokenIterator.hasNext()) {
			return;
		}
		String[] ts = new String[bufSize];
		for (int i = 0; i < bufSize; ++i) {
			ts[i] = genToken();		
		}
		
		CopyOnWriteArrayList<String> newTokens = new CopyOnWriteArrayList<String>(ts);
		tokenIterator = newTokens.iterator();
	}
	
	protected String genToken() {
		return UUID.randomUUID().toString();
		//return "abcdefghijkl";
	}
	
	public String getNextToken() {
		while (!tokenIterator.hasNext()) {
			growToken();
		}
		return tokenIterator.next();
	}

}
